package com.sinochem.sales.admin.service.impl;

import com.sinochem.sales.admin.api.to.UserTO;
import com.sinochem.sales.admin.api.vo.UserVO;
import com.sinochem.sales.admin.service.IUserService;
import org.apache.log4j.Logger;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.exception.BaseException;
import org.sagacity.sqltoy.utils.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    /**
     * 日志
     */
    private final static Logger logger = Logger.getLogger(UserServiceImpl.class);

    @Autowired
    SqlToyLazyDao sqlToyLazyDao;

    private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    private BaseException baseException;

    /**
     * 修改用户登录密码
     *
     * @param userId
     * @param password
     */
    public boolean updateUserPwd(String userId, String password) {
        String newPwd = bCryptPasswordEncoder.encode(password);
        try {
            Long updateCount = this.sqlToyLazyDao.executeSql("update_user_Pwd",
                    new String[]{"userId", "newPwd"}, new Object[]{userId, newPwd});
            if (updateCount != null && updateCount > 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改用户密码操作失败!");
            throw new BaseException("修改用户密码操作失败!", e);
        }
    }

    /**
     * 修改用户信息
     *
     * @param userTO
     */
    public boolean updateUserInfo(UserTO userTO) {
        try {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(userTO, userVO);
            UserVO userVO1 = (UserVO) sqlToyLazyDao.loadBySql("find_userInfo_by_uid", new String[]{"userId"},
                    new Object[]{userVO.getUserId()},
                    UserVO.class);
            if (StringUtil.isNotBlank(userVO.getPassword())) {
                //判断新旧密码是否相同
                if (!bCryptPasswordEncoder.matches(userVO.getPassword(), bCryptPasswordEncoder.encode(userVO1.getPassword()))) {
                    userVO.setPassword(bCryptPasswordEncoder.encode(userVO.getPassword()));
                }
            }
            Long updateCount = sqlToyLazyDao.update(userVO);
            return updateCount != null && updateCount > 0;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改用户信息操作失败!");
            throw baseException;
        }
    }
}